package com.zed.code.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zed.code.base.TResponse;
import com.zed.code.enums.Constant;
import com.zed.code.enums.Operator;
import com.zed.code.response.TokenInfo;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static org.apache.http.client.utils.DateUtils.formatDate;


public class PubFetchTool {

    public static final String DIDI_OPERATOR_ID = "765367656";//运营商滴滴编号
    private static final String OPERATOR_ID = "314838869";
    private static Map<String, String> map = new ConcurrentHashMap<String, String>(3);
    /**
     * post请求的正文信息
     * @param enString
     * @param timeStamp
     * @param sig
     * @return
     */
    public static Map<String, Object> genReqData(Operator operator, String enString, String timeStamp, String sig) {
        Map<String, Object> message = new HashMap<String, Object>();
        message.put("OperatorID", operator.getDdOperatorId());//运营商标识（OperatorID）
        message.put("Data", enString);//加密数据
        message.put("TimeStamp", timeStamp);//时间戳
        message.put("Seq", "0001");//自增序列
        message.put("Sig", sig);//参数签名
        return message;
    }

    public static TResponse genErrorResp(String ret, String msg) {
        TResponse<TokenInfo> resp = new TResponse<TokenInfo>();
        resp.setSig("0");
        resp.setData(null);
        resp.setMsg(msg);
        resp.setRet(ret);
        return resp;
    }
    public static String genSig(Operator operator, String enString, String timeStamp) {
        return HMacMD5.getHmacMd5Str(operator.getSigSecret(), operator.getDdOperatorId() + enString + timeStamp + "0001");
    }

    public static String genDDDecodeData(String jsonData,String AES_KEY,String AES_IV) {
        return EncodeUtil.decrypt(jsonData, AES_KEY, AES_IV);
    }

    public static String genDDEncodeData(String jsonData,String AES_KEY,String AES_IV) {
        return EncodeUtil.encrypt(jsonData,AES_KEY, AES_IV);
    }

    public static String genDDSig(String enString,String SIGN_KEY) {
        return HMacMD5.getHmacMd5Str(SIGN_KEY, enString);
    }
    public static TResponse reqRet(List<String> authorization) throws RuntimeException{
        String token=authorization.get(0);
        if (null!=token){
            token=token.substring(7);
            Boolean is= TokenUtil.verificationToken(token);
            if (!is){
                return genErrorResp("4002","TOKEN错误");
            }
        }else {
            return genErrorResp("4003","POST参数不法，缺少必须的示例");
        }
        return null;
    }
    public static boolean checkSig(JSONObject json, String req_operatorID, String SIGN_KEY) {
        String Data = json.getString("Data");
        String TimeStamp = json.getString("TimeStamp");
        String Seq = json.getString("Seq");
        String Sig = json.getString("Sig");
        String ddSig = HMacMD5.getHmacMd5Str(SIGN_KEY, req_operatorID + Data + TimeStamp + Seq);
        if (Sig.equals(ddSig))
            return true;
        return false;
    }

    /**
     * 处理数据，对Data进行加密后签名 生成处理后的数据
     *
     * @param jsonParam
     * @param aesKey
     * @param aesIV
     * @param signKey
     * @return
     * @throws Exception
     */
    public static JSONObject dealParam(String jsonParam, String aesKey,
                                       String aesIV, String signKey) throws Exception {

        JSONObject paramObj = new JSONObject();
        paramObj.put(Constant.OperatorID, OPERATOR_ID);
        paramObj.put(Constant.Data, AESUtil.Encrypt(jsonParam, aesKey, aesIV));
        String dateStr = formatDate(new Date(), "yyyyMMddHHmmss");
        paramObj.put(Constant.TimeStamp, dateStr);
        paramObj.put(Constant.Seq, getSeq(dateStr));

        String signMsg = paramObj.getString(Constant.OperatorID)
                + paramObj.getString(Constant.Data)
                + paramObj.getString(Constant.TimeStamp)
                + paramObj.getString(Constant.Seq);
        System.out.println("dealParam=" + JSON.toJSONString(paramObj));
        System.out.println("aesKey=" + aesKey+"aesIV=" + aesIV+"signKey=" + signKey);
        paramObj.put(Constant.Sig, HMacMD5.getHmacMd5Str(signKey, signMsg));
        System.out.println("paramObj="+ JSON.toJSONString(paramObj));
        return paramObj;
    }
    /**
     * 处理Seq
     * @param timeStamp
     * @return
     */
    public static String getSeq(String timeStamp) {

        if (map.containsKey(timeStamp)) {
            Integer count = Integer.parseInt(map.get(timeStamp)) + 1;
            switch (count.toString().length()) {
                case 1:
                    map.put(timeStamp, "000" + count);
                    break;
                case 2:
                    map.put(timeStamp, "00" + count);
                    break;
                case 3:
                    map.put(timeStamp, "0" + count);
                    break;
                case 4:
                    map.put(timeStamp, "" + count);
                    break;
                default:
                    map.put(timeStamp, "" + count);
                    break;
            }
            return map.get(timeStamp);
        } else {
            map.put(timeStamp, "0001");
            return "0001";
        }
    }
    public static void main(String[] args) {
        JSONObject paramObj = new JSONObject();
        paramObj.put(Constant.OperatorID, "");
        try {
            paramObj.put(Constant.Data, PubFetchTool.genDDEncodeData( "{\"StationID\": \"fs001\", \"StartTime\": \"2018-10-01\", \"EndTime\": \"2018-12-11\"}", GDEVConfig.AES_KEY,GDEVConfig.AES_IV));
            paramObj.put(Constant.TimeStamp, "20181220165320");
            paramObj.put(Constant.Seq, "0251");
            paramObj.put(Constant.OperatorID,DIDI_OPERATOR_ID);

            String signMsg = paramObj.getString(Constant.OperatorID)
                    + paramObj.getString(Constant.Data)
                    + paramObj.getString(Constant.TimeStamp)
                    + paramObj.getString(Constant.Seq);
            String sign=HMacMD5.getHmacMd5Str(GDEVConfig.SIGN_KEY, signMsg);
            paramObj.put(Constant.Sig,sign);
            System.out.println("json="+paramObj);
            System.out.println("加密sign="+sign);


            String xx=paramObj.getString(Constant.Data);
            System.out.println("xx="+xx);
            xx=PubFetchTool.genDDDecodeData("加密前的数据:",GDEVConfig.AES_KEY,GDEVConfig.AES_IV);
            System.out.println("xx="+xx);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
